import { Body, Controller, Delete, Get, Param, UseGuards, ParseIntPipe, Patch, Post, Query } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './modules/user.entity';
import { getUserDto } from './dto/get-user.dto';
import { CreateUserPipe } from './pipes/create-user.pipe';
import { CreateUserDto } from './dto/create-user.dto';
import { AuthGuard } from '@nestjs/passport';

@Controller('users')
export class UserController {
    constructor(private readonly userService: UserService) {}

    @Get('/profile')
    @UseGuards(AuthGuard('jwt'))
    async getUserProfile(@Query('id', ParseIntPipe) id: string): Promise<any> {
      return await this.userService.find(id);
    }

    @Get('/pronames')
    async getUserName(@Query('username') username: string): Promise<any> {
      const res = await this.userService.finduser(username);
      if (res.id) {
        return {
          code: 200,
          msg: '查询成功！',
          data: [res]
        }
      }
      return {
        code: 400,
        msg: '未查询到内容'
      };
    }

    @Get()
    async getUsers(@Query() query: getUserDto): Promise<any> {
      console.log("🚀 ~ UserController ~ getUsers ~ getUserDto:", query)
      return await this.userService.findAll(query);
    }

    @Post()
    async addUser(@Body(CreateUserPipe) dto: CreateUserDto): Promise<any>{
      const user = dto as User;
      const res = await this.userService.create(user);
      if (res.id) {
        const userData = await this.userService.find(res.id);
        return {
          code: 200,
          msg: '新增成功！',
          data: userData
        }
      }
      return {
        code: 400,
        msg: '新增失败'
      };
    }

    @Patch('/:id')
    async updateUser(@Body() dto: any, @Param('id') id: string): Promise<any> {
      const user = dto as User
      return await this.userService.update(id, user);
    }
    @Delete('/:id')
    async delUser(@Param('id') id: string): Promise<any> {
      const userData = await this.userService.del(id)
      return userData;
    }
}
